<template>
  <div class="profile-page">
    <div class="profile-container">
      <h1 class="page-title">👤 个人信息</h1>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">加载中...</div>
      
      <!-- 用户信息表单 -->
      <div v-else class="profile-form">
        <!-- 头像区域 -->
        <div class="form-group avatar-group">
          <label>头像</label>
          <div class="avatar-container">
            <div v-if="userForm.avatar" class="avatar-wrapper">
              <img 
                :src="userForm.avatar" 
                alt="用户头像" 
                class="avatar-preview"
                @error="handleImageError"
              />
            </div>
            <div v-else class="avatar-placeholder">
              <span class="placeholder-text">暂无头像</span>
            </div>
            <div class="avatar-actions">
              <input 
                type="file" 
                ref="fileInput" 
                accept="image/*" 
                @change="handleAvatarChange" 
                style="display: none;"
              />
              <button @click="triggerFileInput" class="upload-btn">📷 上传头像</button>
            </div>
          </div>
        </div>

        <!-- 账号 -->
        <div class="form-group">
          <label>账号</label>
          <input 
            v-model="userForm.account" 
            type="text" 
            disabled
            class="form-input disabled"
          />
          <span class="hint">账号不可修改</span>
        </div>

        <!-- 昵称 -->
        <div class="form-group">
          <label>昵称</label>
          <input 
            v-model="userForm.nickname" 
            type="text" 
            placeholder="请输入昵称"
            class="form-input"
          />
        </div>

        <!-- 手机号 -->
        <div class="form-group">
          <label>手机号</label>
          <input 
            v-model="userForm.phone" 
            type="tel" 
            placeholder="请输入手机号"
            class="form-input"
          />
        </div>

        <!-- 修改密码区域 -->
        <div class="password-section">
          <h3 class="section-title">🔒 修改密码</h3>
          
          <!-- 原密码 -->
          <div class="form-group">
            <label>原密码 <span class="required">*</span></label>
            <input 
              v-model="passwordForm.oldPassword" 
              type="password" 
              placeholder="请输入原密码"
              class="form-input"
            />
          </div>
          
          <!-- 新密码 -->
          <div class="form-group">
            <label>新密码 <span class="required">*</span></label>
            <input 
              v-model="passwordForm.newPassword" 
              type="password" 
              placeholder="请输入新密码（至少6位）"
              class="form-input"
            />
            <span class="hint">密码长度至少为6位</span>
          </div>
          
          <!-- 确认新密码 -->
          <div class="form-group">
            <label>确认新密码 <span class="required">*</span></label>
            <input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入新密码"
              class="form-input"
            />
          </div>
          
          <!-- 修改密码按钮 -->
          <button 
            @click="handleChangePassword" 
            class="change-password-btn" 
            :disabled="changingPassword"
          >
            {{ changingPassword ? '修改中...' : '🔑 修改密码' }}
          </button>
        </div>

        <!-- 按钮组 -->
        <div class="form-actions">
          <button @click="handleUpdate" class="save-btn" :disabled="updating">
            {{ updating ? '保存中...' : '💾 保存修改' }}
          </button>
          <button @click="loadUserInfo" class="reset-btn">🔄 重置</button>
        </div>

        <!-- 提示信息 -->
        <p v-if="message" :class="['message', messageType]">{{ message }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getUserInfo, updateUser, changePassword } from '../../api/user';
import { uploadFile } from '../../api/file';


const loading = ref(false);
const updating = ref(false);
const changingPassword = ref(false);
const message = ref('');
const messageType = ref(''); // 'success' 或 'error'
const fileInput = ref<HTMLInputElement | null>(null);

const userForm = ref({
  id: 0,
  account: '',
  nickname: '',
  avatar: '',
  phone: ''
});

// 密码修改表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true;
  message.value = '';
  
  try {
    // 从 localStorage 获取当前登录用户ID
    const userId = localStorage.getItem('userId');
    
    if (!userId) {
      message.value = '未登录，请先登录';
      messageType.value = 'error';
      loading.value = false;
      return;
    }
    
    const userIdNum = Number(userId);
    if (isNaN(userIdNum)) {
      message.value = '用户ID无效，请重新登录';
      messageType.value = 'error';
      loading.value = false;
      return;
    }
    
    const res = await getUserInfo(userIdNum);
    
    if (res.success && res.data) {
      userForm.value = {
        id: res.data.id,
        account: res.data.account,
        nickname: res.data.nickname || '',
        avatar: res.data.avatar || '',
        phone: res.data.phone || ''
      };
      
      // 清空密码表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    } else {
      message.value = res.message || '获取用户信息失败';
      messageType.value = 'error';
    }
  } catch (error) {
    console.error('加载用户信息失败:', error);
    message.value = '请求失败，请稍后重试';
    messageType.value = 'error';
  } finally {
    loading.value = false;
  }
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click();
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement;
  // 图片加载失败时，隐藏图片，显示占位符
  userForm.value.avatar = '';
};

// 处理头像上传
const handleAvatarChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    message.value = '请选择图片文件';
    messageType.value = 'error';
    return;
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    message.value = '图片大小不能超过5MB';
    messageType.value = 'error';
    return;
  }
  
  try {
    message.value = '上传中...';
    messageType.value = 'success';
    
    // 获取当前用户ID
    const userId = localStorage.getItem('userId');
    if (!userId) {
      message.value = '未登录，请先登录';
      messageType.value = 'error';
      return;
    }
    
    const res = await uploadFile(file, Number(userId));
    
    if (res.success && res.data?.url) {
      // 立即更新头像显示
      userForm.value.avatar = res.data.url;
      message.value = '头像上传成功，请点击保存修改按钮保存到数据库';
      messageType.value = 'success';
    } else {
      message.value = res.message || '上传失败';
      messageType.value = 'error';
    }
  } catch (error: any) {
    console.error('上传头像失败:', error);
    message.value = error.message || '上传失败，请稍后重试';
    messageType.value = 'error';
  }
};

// 更新用户信息（不包含密码）
const handleUpdate = async () => {
  updating.value = true;
  message.value = '';
  
  try {
    const updateData: any = {
      id: userForm.value.id,
      account: userForm.value.account,
      nickname: userForm.value.nickname,
      avatar: userForm.value.avatar,
      phone: userForm.value.phone
    };
    
    // 注意：密码修改需要通过专门的接口
    const res = await updateUser(updateData);
    
    if (res.success) {
      message.value = '保存成功！';
      messageType.value = 'success';
      // 重新加载数据
      setTimeout(() => {
        loadUserInfo();
      }, 1000);
    } else {
      message.value = res.message || '保存失败';
      messageType.value = 'error';
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    message.value = '保存失败，请稍后重试';
    messageType.value = 'error';
  } finally {
    updating.value = false;
  }
};

// 修改密码
const handleChangePassword = async () => {
  changingPassword.value = true;
  message.value = '';
  
  try {
    // 步骤1：验证输入
    if (!passwordForm.value.oldPassword) {
      message.value = '请输入原密码';
      messageType.value = 'error';
      changingPassword.value = false;
      return;
    }
    
    if (!passwordForm.value.newPassword) {
      message.value = '请输入新密码';
      messageType.value = 'error';
      changingPassword.value = false;
      return;
    }
    
    if (passwordForm.value.newPassword.length < 6) {
      message.value = '新密码长度至少为6位';
      messageType.value = 'error';
      changingPassword.value = false;
      return;
    }
    
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      message.value = '两次输入的新密码不一致';
      messageType.value = 'error';
      changingPassword.value = false;
      return;
    }
    
    // 步骤2：调用修改密码接口
    const res = await changePassword(
      userForm.value.id,
      passwordForm.value.oldPassword,
      passwordForm.value.newPassword
    );
    
    if (res.success) {
      message.value = '密码修改成功！';
      messageType.value = 'success';
      // 清空密码表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    } else {
      message.value = res.message || '密码修改失败';
      messageType.value = 'error';
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    message.value = '修改密码失败，请稍后重试';
    messageType.value = 'error';
  } finally {
    changingPassword.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserInfo();
});
</script>

<style scoped>
.profile-page {
  padding: 20px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
  width: 100%;
}

.profile-container {
  max-width: 600px;
  margin: 0 auto;
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 16px;
}

.profile-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #52C41A;
}

.form-input.disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
  color: #999;
}

.hint {
  font-size: 12px;
  color: #999;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

/* 密码修改区域 */
.password-section {
  margin-top: 30px;
  padding-top: 30px;
  border-top: 2px solid #f0f0f0;
}

.section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.change-password-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
  margin-top: 10px;
}

.change-password-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.change-password-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 头像区域 */
.avatar-group {
  align-items: center;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-wrapper {
  width: 100px;
  height: 100px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #52C41A;
  background-color: #f5f5f5;
  display: block;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 3px solid #d9d9d9;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-text {
  color: #999;
  font-size: 14px;
  text-align: center;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
}

.upload-btn {
  padding: 10px 20px;
  background-color: #52C41A;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.upload-btn:hover {
  background-color: #389e0d;
  transform: translateY(-2px);
}

/* 按钮组 */
.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.save-btn,
.reset-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.save-btn {
  background: linear-gradient(135deg, #52C41A 0%, #389e0d 100%);
  color: white;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.reset-btn:hover {
  background-color: #e8e8e8;
}

/* 消息提示 */
.message {
  margin-top: 10px;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.message.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 响应式 */
@media (max-width: 768px) {
  .profile-container {
    padding: 20px;
  }
  
  .avatar-container {
    flex-direction: column;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
